const express = require('express');
const router = express.Router();
const { NotFound } = require('http-errors');
const { success, failure } = require('../../utils/responses');
const { delKey } = require('../../utils/redis');

const {Setting, Course, Chapter } = require('../../models')
const { coursesIndex, chaptersIndex} = require('../../utils/meilisearch')
/**
 * 白名单参数过滤
 * */
const filterBody = (data) => {
  return {
    name: data.name,
    icp: data.icp,
    copyright: data.copyright,
  };
};

/**
 * 公共方法: 查询当前系统设置
 * */

async function getSetting() {
  const setting = await Setting.findOne();
  if (!setting) {
    throw new NotFound(`初始系统未找到，请运行种子文件`);
  }
  return setting;
}

/**
 * 查询系统设置详情
 * */
router.get('/', async function (req, res) {
  try {
    const settings = await getSetting();
    success(res, '查询成功', { settings });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 更新系统设置
 * */
router.put('/', async function (req, res) {
  try {
    const setting = await getSetting();
    const body = filterBody(req.body);
    const data = await setting.update(body);
    console.log(123);
    // 删除redis缓存
    await delKey('setting');
    success(res, '更新成功', data);
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 重建merlisearch 索引
 * Get /admin/setting/meilisearch_reindex
 * */ 

router.get('/meilisearch_reindex', async function(req, res) {
  try {
    // 课程
    const courses = await Course.findAll({
      attributes: ['id', 'name', 'image', 'content', 'likesCount', 'updatedAt']
    })
    await coursesIndex.addDocuments(courses)
    // 章节
    const chapters = await Chapter.findAll({
      attributes: ['id', 'title', 'content', 'updatedAt']
    })
    await chaptersIndex.addDocuments(chapters)
    success(res, '重建成功')
  } catch (error) {
    failure(res, error)
  }
}) 


module.exports = router;
